import type { Plugin } from 'vite'
import { createFilter } from 'vite'

export function modifyPopupHtmlAssetsPath(): Plugin {
  const filter = createFilter('dist/popup/popup.html')

  return {
    name: 'vite-plugin-modify-asset-paths',
    enforce: 'pre',
    transformIndexHtml: {
      async handler(html: string): Promise<string> {
        const modifiedHtml = html.replace(/src="(\/assets\/[^"]*)"/g, `src="/popup$1"`).replace(/href="(\/assets\/[^"]*)"/g, `href="/popup$1"`)

        return modifiedHtml
      },
    },
    configResolved(config: any) {
      filter(config.input)
    },
  }
}
